﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Sprout.Core;
using Sprout.Core.Paging;
using Sprout.Schedule.Dtos;
using Sprout.Schedule.Enums;
using Sprout.Schedule.Interfaces;

namespace Sprout.Schedule.Web.Controllers
{
    /// <summary>
    /// 调度中心
    /// </summary>
    public class ScheduleController : BaseController
    {
        IJobManagerService jobManagerService = ServiceLocator.GetService<IJobManagerService>();
        ITaskService taskService = ServiceLocator.GetService<ITaskService>();
        ITaskLogService taskLogService = ServiceLocator.GetService<ITaskLogService>();

        #region 视图
        /// <summary>
        /// 列表
        /// </summary>
        /// <returns></returns>
        [ApiExplorerSettings(IgnoreApi = true)]
        public IActionResult Index()
        {
            return View();
        }

        [ApiExplorerSettings(IgnoreApi = true)]
        public IActionResult Insert()
        {
            return View();
        }

        [ApiExplorerSettings(IgnoreApi = true)]
        public IActionResult UpdateRunValue()
        {
            return View();
        }
        [ApiExplorerSettings(IgnoreApi = true)]
        public IActionResult TaskLogs()
        {
            return View();
        }
        [ApiExplorerSettings(IgnoreApi = true)]
        public IActionResult Update()
        {
            return View();
        }
        [ApiExplorerSettings(IgnoreApi = true)]
        public IActionResult DeleteLog(long taskId)
        {
            ViewBag.TaskId = taskId;
            return View();
        }


        #endregion

        #region 接口

        /// <summary>
        /// 获取所有计划任务
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IList<TaskInfo>> GetTasks()
        {
            return await taskService.Gets(new TaskQuery());
        }

        /// <summary>
        /// 根据ID获取计划任务
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<TaskInfo> GetTaskById(long id)
        {
            return await taskService.GetDetailAsync(id);
        }

        /// <summary>
        /// 修改计划任务
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task UpdateTask(TaskInfo dto)
        {
            var taskInfo = await taskService.GetDetailAsync(dto.Id);
            if (taskInfo.CronExpression != dto.CronExpression)
            {
                await jobManagerService.UpdateJob(dto.Id, dto.CronExpression);
            }
            await taskService.Update(dto);
            if (taskInfo.JobFullName != dto.JobFullName)
            {
                //删除任务
                await jobManagerService.RemoveJob(dto.Id);
                //新增任务
                taskInfo = await taskService.GetDetailAsync(dto.Id);
                await jobManagerService.StartJob(dto);
            }
        }

        /// <summary>
        /// 修改计划任务最后执行的信息
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task UpdateRunValue(TaskInfo dto)
        {
            await taskService.UpdateRunValueAsync(dto.Id, dto.RunValue);
        }

        /// <summary>
        /// 删除计划任务
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task Delete(TaskInfo dto)
        {
            await jobManagerService.RemoveJob(dto.Id);
            await taskService.Delete(dto.Id);
        }

        /// <summary>
        /// 暂停任务
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task PauseJob(TaskInfo dto)
        {
            await jobManagerService.PauseJob(dto.Id);
            await taskService.UpdateStatus(dto.Id, TaskStatusEnum.Disabled);
        }

        /// <summary>
        /// 恢复任务
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task ResumeJob(TaskInfo dto)
        {
            await jobManagerService.ResumeJob(dto.Id);
            await taskService.UpdateStatus(dto.Id, TaskStatusEnum.Enabled);
        }

        /// <summary>
        /// 立即执行
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task TriggerJob(TaskInfo dto)
        {
            var task = await taskService.GetDetailAsync(dto.Id);
            if(task.RunStatus== TaskRunStatusEnum.Running)
            {
                throw new Exception("任务正在执行，不能重复执行");
            }
            await jobManagerService.TriggerJob(dto.Id);
        }

        /// <summary>
        /// 新增计划任务
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task Insert(TaskInfo dto)
        {
            var id = await taskService.Insert(dto);
            dto.Id = id;
            await jobManagerService.StartJob(dto);
        }

        /// <summary>
        /// 中止任务
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task Interrupt(TaskInfo dto)
        {
            await taskService.Interrupt(dto.Id);
            await jobManagerService.Interrupt(dto.Id);
        }

        /// <summary>
        /// 载入任务（开始任务）
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task StartJob(TaskInfo dto)
        {
            var taskInfo = await taskService.GetDetailAsync(dto.Id);
            if (taskInfo.RunStatus == TaskRunStatusEnum.Stop)
            {
                await jobManagerService.StartJob(dto);
            }
        }

        /// <summary>
        /// 重新初始化所有任务
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task Initialize()
        {
            await jobManagerService.Initialize();
        }

        /// <summary>
        /// 分页查询日志记录
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<PagedList<TaskLog>> GetLogPaging([FromQuery] TaskLogQuery query)
        {
            return await taskLogService.GetPaging(query);
        }

        /// <summary>
        /// 删除日志
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<int> DeleteLog(TaskLog dto)
        {
            return await taskLogService.Delete(dto);
        }

        #endregion
    }
}
